package com.example.take_out_dish.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.take_out_dish.common.Result;
import com.example.take_out_dish.dto.DishDTO;
import com.example.take_out_dish.entity.Category;
import com.example.take_out_dish.entity.Dish;
import com.example.take_out_dish.service.DishService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author yyyyys
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Resource
    private DishService dishService;


    @GetMapping("/page")
    public Result<Page<DishDTO>> page(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String categoryId,
            @RequestParam(required = false) Integer status) {
        log.info("page: {}, pageSize: {}, name: {}, categoryId: {}, status: {}", page, pageSize, name, categoryId, status);
        Page<DishDTO> dishDTOPage = dishService.pageWithCategoryName(page, pageSize, name, categoryId, status);
        return Result.success(dishDTOPage);
    }
    @PutMapping()
    public Result<Object> update(@RequestBody Dish dish){
        dishService.updateById(dish);
        return Result.success();
    }

    @DeleteMapping()
    public Result<Object> deleteById(@RequestParam("ids") String id){
        Dish dish = dishService.getById(id);
        dish.setIsDeleted(1);
        dishService.updateById(dish);
        return Result.success();
    }

    @PostMapping("/status")
    public Result<Object> updateStatus(@RequestParam("id") String id){
        Dish dish = dishService.getById(id);
        if (dish.getStatus()==0){
            dish.setStatus(1);
        }else {
            dish.setStatus(0);
        }
        dishService.updateById(dish);
        return Result.success();
    }

    @PostMapping("/saveDish")
    public Result<Object> save(@RequestBody Dish dish){
        dishService.saveDish(dish);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result<Object> getId(@PathVariable String id){
        dishService.getById(id);
        return Result.success(dishService.getById(id));
    }
    @GetMapping("/list")
    public Result<Object> list(Dish dish){
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getStatus,1);
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list=dishService.list(wrapper);
        return Result.success(list);
    }




}
